import { createRouter, createWebHashHistory } from "vue-router"
import { useRouteStore } from "@/store/route"
import { getRouteList } from "@/api/route"

// 定义基本路由配置
const routes = [
  {
    path: "/:pathMatch(.*)",
    meta: { title: "404" },
    name: "404",
    component: () => import("@/views/error/404.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/Login.vue"),
    meta: { title: "登录" },
  },
  {
    path: "/",
    name: "layout",
    component: () => import("@/views/layout/Layout.vue"),
    redirect: "/home",
    children: [], // 初始时没有子路由
  },
]

export const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
})

// 添加动态路由
const addRoute = () => {
  const routeStore = useRouteStore()
  if (routeStore.isUpdate) {
    routeStore.routeList.forEach((item) => {
      if (!router.hasRoute(item.name)) {
        router.addRoute("layout", {
          path: item.path,
          name: item.name,
          component: () => import(`@/views/${item.name}/index.vue`),
        })
      }
    })
    routeStore.isUpdate = false
  }
}

// 初始化路由
export const initRouter = async () => {
  let routeList = sessionStorage.getItem("routeList")
    ? JSON.parse(sessionStorage.getItem("routeList"))
    : await getRouteList()
  const routeStore = useRouteStore()
  routeStore.updateRouteList(routeList)
  addRoute()
}

// 路由守卫，用于处理路由跳转前的逻辑
router.beforeEach(async (to, from, next) => {
  // 添加动态路由
  addRoute()
  // 判断是否已登录且没有 token，未登录时重定向到登录页
  const token = localStorage.getItem("token")
  if (to.path !== "/login" && !token) {
    return next({ name: "login" })
  }
  next()
})
